package com.varian.tool.extend;

import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 判断器，可以进行条件判断，如果满足条件，执行后续操作
 *
 * @author ben
 * @since 2024/6/24
 */
public class Conditioner<P> {

    private boolean selected = false;
    private Consumer<P> consumer;
    private final P param;

    public Conditioner(P param) {
        this.param = param;
    }

    public static <P> Conditioner<P> of(P p) {
        return new Conditioner<>(p);
    }

    public Conditioner<P> then(Predicate<P> tester, Consumer<P> consumer) {
        if (!selected) {
            if (tester.test(param)) {
                this.consumer = consumer;
                this.selected = true;
            }
        }
        return this;
    }

    public Conditioner<P> thenTrue(Consumer<P> consumer) {
        return then(Boolean.TRUE::equals, consumer);
    }

    public Conditioner<P> thenFalse(Consumer<P> consumer) {
        return then(Boolean.FALSE::equals, consumer);
    }

    public void or(Consumer<P> consumer) {
        if (selected) {
            this.consumer.accept(param);
        } else {
            consumer.accept(param);
        }
    }

    public void end() {
        if (selected) {
            this.consumer.accept(param);
        }
    }
}